# 第一阶段：构建环境，将应用打包为二进制文件
FROM m.daocloud.io/docker.io/library/python:3.9-slim AS builder

WORKDIR /build

# 安装PyInstaller所需的系统依赖
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    binutils && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# 设置pip镜像源
RUN pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple \
    && pip config set global.trusted-host pypi.tuna.tsinghua.edu.cn

# 复制依赖文件并安装依赖和PyInstaller
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt && \
    pip install --no-cache-dir pyinstaller

# 复制项目文件
COPY api_server.py .
COPY redis_company_data.py .
COPY db_connection.py .
COPY .env .
COPY json_files/ json_files/

# 使用PyInstaller打包应用为单个二进制文件
RUN pyinstaller --onefile \
    --hidden-import=fastapi \
    --hidden-import=uvicorn \
    --hidden-import=uvicorn.logging \
    --hidden-import=uvicorn.lifespan \
    --hidden-import=uvicorn.lifespan.on \
    --hidden-import=uvicorn.lifespan.off \
    --hidden-import=uvicorn.protocols \
    --hidden-import=uvicorn.protocols.http \
    --hidden-import=uvicorn.protocols.http.auto \
    --hidden-import=uvicorn.protocols.websockets \
    --hidden-import=uvicorn.protocols.websockets.auto \
    --hidden-import=redis \
    --hidden-import=python-dotenv \
    --hidden-import=pydantic \
    --hidden-import=requests \
    --hidden-import=python-multipart \
    api_server.py

# 第二阶段：使用Ubuntu 22.04基础镜像运行二进制文件
FROM m.daocloud.io/docker.io/library/ubuntu:22.04

# 设置工作目录
WORKDIR /app

# 安装运行二进制文件所需的最小依赖
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    ca-certificates && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# 复制构建阶段生成的二进制文件
COPY --from=builder /build/dist/api_server /app/api-server
RUN chmod +x /app/api-server

# 复制需要的数据文件
# COPY --from=builder /build/.env /app/
COPY --from=builder /build/json_files/ /app/json_files/

# 创建非特权用户并设置权限
RUN useradd -m appuser && \
    chown -R appuser:appuser /app
USER appuser

# 暴露端口
EXPOSE 8000

# 启动命令
CMD ["/app/api-server"] 